<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-container" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input
              v-model="queryParams.categoryName"
              placeholder="请输入分类名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="分类编码" prop="categoryCode">
            <el-input
              v-model="queryParams.categoryCode"
              placeholder="请输入分类编码"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['iot:category:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['iot:category:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['iot:category:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['iot:category:export']">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="categoryId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分类名称" prop="categoryName" min-width="200" />
        <el-table-column label="分类编码" prop="categoryCode" min-width="120" />
        <el-table-column label="显示顺序" prop="orderNum" width="100" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.status === '0'" 
              type="success"
            >
              正常
            </el-tag>
            <el-tag 
              v-else-if="scope.row.status === '1'" 
              type="danger"
            >
              停用
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:category:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['iot:category:add']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:category:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改产品分类对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body @close="closeDialog">
      <el-form ref="categoryFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="categoryOptions"
                :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
                value-key="categoryId"
                placeholder="选择上级分类"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编码" prop="categoryCode">
              <el-input v-model="form.categoryCode" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类图标" prop="icon">
              <el-input v-model="form.icon" placeholder="请输入分类图标" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductCategory" lang="ts">
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from '@/api/iot/category'
import { IotProductCategoryVO, IotProductCategoryQuery, IotProductCategoryForm } from '@/api/iot/category/types'
import { handleTree } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const categoryList = ref<IotProductCategoryVO[]>([])
const buttonLoading = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<Array<string | number>>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)

const queryFormRef = ref<ElFormInstance>()
const categoryFormRef = ref<ElFormInstance>()

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
})

const initFormData: IotProductCategoryForm = {
  categoryId: undefined,
  parentId: 0,
  categoryName: '',
  categoryCode: '',
  orderNum: 0,
  icon: '',
  description: '',
  status: '0'
}

const queryParams = ref<IotProductCategoryQuery>({
  pageNum: 1,
  pageSize: 10,
  categoryName: '',
  categoryCode: '',
  parentId: undefined,
  status: ''
})

const form = ref<IotProductCategoryForm>({ ...initFormData })

const rules = reactive<FormRules<IotProductCategoryForm>>({
  categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  categoryCode: [{ required: true, message: '分类编码不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }]
})

const categoryOptions = ref<IotProductCategoryVO[]>([])

/** 查询产品分类列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listCategory(queryParams.value)
    
    // 根据实际返回的数据结构处理
    let data = []
    
    // 尝试多种可能的数据结构
    if (res.data && res.data.rows && Array.isArray(res.data.rows)) {
      data = res.data.rows
    } else if (res.data && Array.isArray(res.data)) {
      data = res.data
    } else if (res.rows && Array.isArray(res.rows)) {
      data = res.rows
    } else if (Array.isArray(res)) {
      data = res
    }
    
    if (!Array.isArray(data)) {
      console.warn('API 返回的数据不是数组:', data)
      data = []
    }
    
    // 使用导入的 handleTree 方法，正确传递字段名
    categoryList.value = handleTree(data, 'categoryId', 'parentId', 'children')
  } catch (error) {
    console.error('获取分类列表失败:', error)
    categoryList.value = []
  } finally {
    loading.value = false
  }
}

/** 查询产品分类下拉树结构 */
const getTreeselect = async () => {
  try {
    const res = await listCategory()
    
    // 根据实际返回的数据结构处理
    let data = []
    
    // 尝试多种可能的数据结构
    if (res.data && res.data.rows && Array.isArray(res.data.rows)) {
      data = res.data.rows
    } else if (res.data && Array.isArray(res.data)) {
      data = res.data
    } else if (res.rows && Array.isArray(res.rows)) {
      data = res.rows
    } else if (Array.isArray(res)) {
      data = res
    }
    
    if (!Array.isArray(data)) {
      console.warn('下拉树数据不是数组:', data)
      data = []
    }
    
    // 使用导入的 handleTree 方法，正确传递字段名
    categoryOptions.value = handleTree(data, 'categoryId', 'parentId', 'children')
  } catch (error) {
    console.error('获取分类下拉树失败:', error)
    categoryOptions.value = []
  }
}

/** 表单重置 */
const reset = () => {
  form.value = JSON.parse(JSON.stringify(initFormData))
  
  categoryFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = (row?: IotProductCategoryVO) => {
  reset()
  getTreeselect()
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId
  } else {
    form.value.parentId = 0
  }
  dialog.visible = true
  dialog.title = '添加产品分类'
}

/** 修改按钮操作 */
const handleUpdate = async (row?: IotProductCategoryVO) => {
  reset()
  getTreeselect()
  const categoryId = row?.categoryId || ids.value[0]
  const res = await getCategory(categoryId)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改产品分类'
}

/** 提交按钮 */
const submitForm = () => {
  categoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true
      try {
        if (form.value.categoryId != null) {
          await updateCategory(form.value)
          proxy?.$modal.msgSuccess('修改成功')
        } else {
          await addCategory(form.value)
          proxy?.$modal.msgSuccess('新增成功')
        }
        dialog.visible = false
        await getList()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        buttonLoading.value = false
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (row?: IotProductCategoryVO) => {
  const categoryIds = row?.categoryId || ids.value
  await proxy?.$modal.confirm('是否确认删除产品分类编号为"' + categoryIds + '"的数据项？')
  try {
    await delCategory(categoryIds)
    await getList()
    proxy?.$modal.msgSuccess('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('iot/category/export', {
    ...queryParams.value
  }, `category_${new Date().getTime()}.xlsx`)
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: IotProductCategoryVO[]) => {
  ids.value = selection.map(item => item.categoryId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false
  reset()
}

/** 关闭对话框 */
const closeDialog = () => {
  dialog.visible = false
  reset()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}
</style>